<template>
    <el-form
        :inline="true"
        ref="searchFormRef"
        style="max-width: 100%"
        label-width="auto"
        :model="queryConditions"
        class="demo-ruleForm"
        status-icon
    >
        <el-form-item label="单据编号" prop="code">
            <el-input
                v-model="queryConditions.code"
                style="width: 200px"
                size="large"
                placeholder="请输入"
                :suffix-icon="Search"
                clearable
            />
        </el-form-item>
        <el-form-item label="客户" prop="customerId">
            <el-select
                v-model="queryConditions.customerId"
                style="width: 200px"
                size="large"
                placeholder="请选择"
                clearable
            >
                <el-option
                    v-for="customer in customerList"
                    :key="customer.id"
                    :label="customer.name"
                    :value="customer.id"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="发票号" prop="invoiceNum">
            <el-input
                v-model="queryConditions.invoiceNum"
                style="width: 200px"
                size="large"
                placeholder="请输入"
                :suffix-icon="Search"
                clearable
            />
        </el-form-item>
        <el-button type="primary" :icon="Search" @click="search">查询</el-button>
        <el-button type="primary" :icon="RefreshRight" @click="resetForm">重置</el-button>
    </el-form>
    <!-- 隐藏的文件输入框，用于导入 -->
    <input
        type="file"
        ref="fileInput"
        style="display: none"
        accept=".xlsx,.xls"
        @change="handleFileSelect"
    />
    <TestPage :table-data="formattedTableData"
              :columns="tableColumns"
              :current-page="pageNo"
              :total="allPage"
              :page-size="pageSize"
              @page-change="handlePageChange"
              @action="handleTableAction"
              @edit="handleEditAction"
              @delete="handleDeleteAction"
              @code-click="handleEditAction"
              @print="handlePrint"
    />
    <!-- 明细弹窗 -->
    <!--    <el-dialog title="销售发票明细" v-model="dialogVisible" width="80%">-->
    <!--        <el-table :data="selectedRow.details" stripe>-->
    <!--            <el-table-column-->
    <!--                v-for="col in detailColumns"-->
    <!--                :key="col.prop"-->
    <!--                :prop="col.prop"-->
    <!--                :label="col.label"-->
    <!--                :width="col.width"-->
    <!--                :formatter="col.formatter"-->
    <!--            />-->
    <!--        </el-table>-->
    <!--        <div v-if="!selectedRow.details || selectedRow.details.length === 0" style="text-align: center; padding: 20px;">-->
    <!--            无明细数据-->
    <!--        </div>-->
    <!--    </el-dialog>-->
</template>

<script setup lang="ts">
import {onMounted} from 'vue';
import {Search, RefreshRight} from '@element-plus/icons-vue';
import {ref, computed, reactive, nextTick} from 'vue';
import {ElMessageBox, ElMessage, type FormInstance} from 'element-plus';
import request from '@/util/request'
import TestPage from "@/test/TestPage.vue";
import type {SalesInvoice} from "@/types/public-xs/SalesInvoice.ts";
import {useRouter} from 'vue-router';

let pageNo = ref(1);
let pageSize = ref(5);
let allPage = ref(0);
let router = useRouter();
const searchFormRef = ref<FormInstance>();
const fileInput = ref<HTMLInputElement | null>(null); // 文件输入框引用

// 单据编号弹窗
// const dialogVisible = ref(false);
// const selectedRow = ref<SalesInvoice>({ details: [] });

// 查询
const search = () => {
    pageNo.value = 1; // 重置到第一页
    fetchData(1);
};

// 重置表单
const resetForm = () => {
    if (!searchFormRef.value) return;
    nextTick(() => {
        searchFormRef.value!.resetFields();
        pageNo.value = 1;
        fetchData(1);
    });
};

// 查询条件
const queryConditions = reactive({
    code: '',
    customerId: '',
    invoiceNum: ''
});

let tableData = ref<SalesInvoice[]>([]);
// 计算属性，将主键字段变为序号，格式化字段
const formattedTableData = computed(() => {
    return tableData.value.map((item, index) => ({
        ...item,
        index: (pageNo.value - 1) * pageSize.value + index + 1,
        code_state: formatCodeState(item.codeState),
        invoice_type: formatInvoiceType(item.invoiceType),
        code_date: formatDate(item.codeDate),
        order_creation_time: formatDate(item.orderCreationTime),
        modify_time: formatDate(item.modifyTime),
        customer: customerList.value.find(c => c.id === item.customerId)?.name || item.customerId || '-'
    }));
});

const formatCodeState = (codeState: number | string) => {
    const state = Number(codeState);
    switch (state) {
        case 0:
            return '已作废';
        case 1:
            return '未审核';
        case 2:
            return '未执行';
        case 3:
            return '已执行';
        default:
            return '未知状态';
    }
};

const formatInvoiceType = (invoiceType: number | string) => {
    const type = Number(invoiceType);
    switch (type) {
        case 0:
            return '普通';
        case 1:
            return '红冲';
        case 2:
            return '退货';
        default:
            return '未知类型';
    }
};

const formatDate = (date: string | Date | undefined) => {
    if (!date) return '-';
    const d = new Date(date);
    return d.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
};

// 主表列定义
const tableColumns = ref([
    {prop: 'index', label: '序号', width: 80},
    {prop: 'code', label: '单据编号', width: 180},
    {prop: 'code_date', label: '单据日期', width: 180},
    {prop: 'invoice_type', label: '发票类型', width: 120},
    {prop: 'customer', label: '客户', width: 150},
    {prop: 'invoiceNum', label: '发票号', width: 120},
    {prop: 'code_state', label: '发票状态', width: 120},
    {prop: 'originalOrderNum', label: '源单号', width: 150},
    {prop: 'amount', label: '金额', width: 120},
    {prop: 'order_creation_time', label: '制单时间', width: 180},
    {prop: 'orderCreator', label: '制单人', width: 120},
    {prop: 'orderDepartment', label: '制单部门', width: 120},
    {prop: 'modify_time', label: '修改时间', width: 180},
    {prop: 'modifier', label: '修改人', width: 120},
]);

// 明细表列定义
const detailColumns = ref([
    {prop: 'invoiceCode', label: '销售发票编号', width: 180},
    {prop: 'goodId', label: '商品ID', width: 100},
    {prop: 'quantity', label: '数量', width: 100},
    {prop: 'actualPrice', label: '实际单价', width: 120},
    {prop: 'tax', label: '税额', width: 100},
    {prop: 'discountRate', label: '折扣率', width: 100},
    {prop: 'notes', label: '备注', width: 200},
    {prop: 'createBy', label: '创建人', width: 120},
    {
        prop: 'createTime',
        label: '创建时间',
        width: 180,
        formatter: (row: any) => formatDate(row.createTime),
    },
    {prop: 'updateBy', label: '更新人', width: 120},
    {
        prop: 'updateTime',
        label: '更新时间',
        width: 180,
        formatter: (row: any) => formatDate(row.updateTime),
    },
    {prop: 'warehouseId', label: '仓库ID', width: 100},
]);

// 显示明细弹窗
// const showDetails = (row: SalesInvoice) => {
//     selectedRow.value = row;
//     dialogVisible.value = true;
// };

const handlePageChange = (newPage: number) => {
    pageNo.value = newPage;
    fetchData(1);
};

const handleTableAction = (actionName: string, selectedRows?: any[]) => {
    console.log('触发操作:', actionName);
    if (actionName === 'add') {
        router.push('/home/fp/addXSFP');
    }
    if (actionName === 'import') {
        fileInput.value?.click(); // 触发文件选择
    }
    if (actionName === 'export') {
        handleExport(selectedRows); // 触发导出
    }
    if (actionName === 'downLoadTemplate') {
        handleDownloadTemplate();
    }
    if (actionName === 'print') {
        handlePrint(selectedRows);
    }

};


// 导出销售发票数据
const handleExport = async (selectedRows?: any[]) => {
    // 过滤掉前端添加的额外字段
    const filteredRows = selectedRows ? selectedRows.map(row => {
        console.log(selectedRows)
        console.log(row)
        const {index, code_date, order_creation_time, modify_time, ...rest} = row;
        console.log(rest)
        return rest;
    }) : [];
    console.log('过滤后的 filteredRows:', filteredRows);
    const params = {
        pageNo: pageNo.value,
        pageSize: pageSize.value,
        code: queryConditions.code,
        customerId: queryConditions.customerId,
        invoiceNum: queryConditions.invoiceNum,
        selectedRows: filteredRows || [] // 包含选中行
        // name: queryConditions.name,
        // phoneNum: queryConditions.phoneNum,
    };
    // const loading = ElLoading.service({text: "正在导出..."});
    try {
        const response = await request.post("/xs/salesInvoice/export", params, {
            responseType: "blob",
        });
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "销售发票信息表.xlsx");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success("导出成功");
    } catch (error) {
        console.error("导出失败:", error);
        ElMessage.error("导出失败，请稍后重试");
    } finally {
        // loading.close();
    }
};

//下载模板
const handleDownloadTemplate = async () => {
    try {
        const response = await request.get('/xs/salesInvoice/template', {
            responseType: 'blob',
        });
        console.log(response)
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '销售发票表.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success('模板下载成功');
    } catch (error) {
        ElMessage.error('模板下载失败，请稍后重试');
    }
}

// 导入
const handleFileSelect = async (event: Event) => {
    const input = event.target as HTMLInputElement;
    const file = input.files?.[0];
    if (!file) {
        ElMessage.warning('未选择文件');
        return;
    }

    // 校验文件后缀
    const allowedExtensions = ['.xlsx', '.xls'];
    const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
    if (!allowedExtensions.includes(fileExtension)) {
        ElMessage.error('文件格式不正确，仅支持 .xlsx 和 .xls 文件');
        input.value = ''; // 重置文件输入框
        return;
    }

    // 校验文件大小
    const maxFileSize = 10 * 1024 * 1024; //10MB
    if (file.size > maxFileSize) {
        ElMessage.error(`文件大小超过限制，最大允许10MB，当前文件大小'${file.size.toFixed(2)}MB'`);
        input.value = ''; //重置
        return;
    }

    const formData = new FormData();
    formData.append('file', file);

    // const loading = ElLoading.service({text: '正在导入...'});
    try {
        const response = await request.post('/xs/salesInvoice/import', formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        });
        console.log(response.data.msg, ",", response.data.code)
        if (response.data.code === '200') {
            ElMessage.success('导入成功');
            await fetchData(pageNo.value); // 刷新表格数据
        } else {
            ElMessage.error(response.data.msg || "导入失败！");
        }
    } catch (error) {
        ElMessage.error('导入失败，请稍后重试');
        console.log(error)
    } finally {
        // loading.close();
        input.value = ''; // 重置文件输入框
    }
};

// 打印销售发票数据
const handlePrint = async (row: any) => {
    console.log(row)
    const params = {
        // pageNo: pageNo.value,
        // pageSize: pageSize.value,
        // code: queryConditions.code,
        // customerId: queryConditions.customerId,
        // invoiceNum: queryConditions.invoiceNum
        row: {
            code: row.code,
            codeDate: row.codeDate,
            invoiceType: row.invoiceType,
            invoice_type: row.invoice_type,
            // customerId:row.customerId,
            customer: row.customer,
            code_state: row.code_state,
            // supplierName: row.supplierName,

            details: row.details,
            // invoiceNum: row.invoiceNum,
            codeState: row.codeState,
            originalOrderNum: row.originalOrderNum,
            amount: row.amount,
            orderCreationTime: row.orderCreationTime,
            orderCreator: row.orderCreator,
            orderDepartment: row.orderDepartment,
            modifyTime: row.modifyTime,
            modifier: row.modifier,
            isDelete: row.isDelete
        }
    };
    console.log(params)
    try {
        const response = await request.post("/xs/salesInvoice/print", params, {
            responseType: "blob",
        });
        const url = window.URL.createObjectURL(new Blob([response.data], {type: 'application/pdf'}));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "销售发票信息表.pdf");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success("打印成功");
    } catch (error) {
        console.error("打印失败:", error);
        ElMessage.error("打印失败，请稍后重试");
    }
};


// 修改
const handleEditAction = (salesInvoice: SalesInvoice) => {
    if (salesInvoice.code) {
        router.push({
            name: 'UpdateSalesInvoice',
            params: {code: salesInvoice.code}
        });
    } else {
        ElMessage.error('单据编号不存在，无法跳转到修改页面');
    }
};

const handleDeleteAction = async (salesInvoice: SalesInvoice) => {
    try {
        await ElMessageBox.confirm('确定删除此销售发票？此操作不可恢复。', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        await request.post(`/xs/salesInvoice/deleteSalesInvoice?id=${salesInvoice.id}`);
        ElMessage.success('删除成功');
        await fetchData(pageNo.value); // 刷新
    } catch (error) {
        ElMessage.error('删除失败，请稍后重试');
    }
};

async function fetchData(page: number) {
    try {
        let response = await request.post('/xs/salesInvoice/selectSalesInvoiceByPage', {
            pageNo: page,
            pageSize: pageSize.value,
            code: queryConditions.code,
            customerId: queryConditions.customerId,
            invoiceNum: queryConditions.invoiceNum
        });
        tableData.value = response.data.data.list;
        allPage.value = response.data.data.total;
        console.log(tableData.value);
    } catch (error) {
        ElMessage.error('获取销售发票数据失败');
        tableData.value = [];
        allPage.value = 0;
    }
}

// 存储所有客户
const customerList = ref<any[]>([]);
const fetchAllSalesInvoice = async () => {
    try {
        const res = await request.post('/basic/Customer/selectAllCustomer');
        customerList.value = res.data.data;
    } catch (e) {
        ElMessage.error('获取客户数据失败');
        console.error('Error fetching customers:', e);
        customerList.value = [];
    }
};

onMounted(() => {
    fetchData(1);
    fetchAllSalesInvoice();
});
</script>

<style scoped>
</style>
